﻿using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.UI.Selection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZhuXingFamilys.CADInformation.Entity;
using ZhuXingFamilys.CADInformation.Utils;
using ZhuXingFamilys.Help;
using NPOI.SS.Formula.Functions;
using Line = Autodesk.Revit.DB.Line;
using System.Diagnostics;
using static System.Net.Mime.MediaTypeNames;
using MySqlX.XDevAPI;
using System.Security.Cryptography;
using NPOI.SS.Formula.Atp;
using System.Collections;
using static Google.Protobuf.Reflection.SourceCodeInfo.Types;
using MySqlX.XDevAPI.Common;
using MS.WindowsAPICodePack.Internal;
using NPOI.OpenXmlFormats.Vml;
using System.Dynamic;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using Teigha.Runtime;
using System.Reflection;
using Autodesk.AutoCAD.EditorInput;
using System.IO;
using Autodesk.AutoCAD.Geometry;

namespace ZhuXingFamilys.CADInformation
{
    /// <summary>
    /// LayerRecognition.xaml 的交互逻辑
    /// </summary>
    public partial class LayerRecognition : Window
    {
        private UIApplication uiApp;
        CADInfo CAD;
        // 选中的线层
        List<SelectedLayers> lineCategories = new List<SelectedLayers>();
        // 选中的符层
        List<SelectedLayers> symbolCategories = new List<SelectedLayers>();
        public LayerRecognition(UIApplication UIApp, CADInfo cad)
        {
            this.CAD = cad;
            this.uiApp = UIApp;
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false; //加载时 取消跨线程检查
        }
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //lineText.Content = CAD.classification + "线层";
            //symbolText.Content = CAD.classification + "符层";

            lineText.Content = "线层";
            symbolText.Content = "符层";

        }
        private void Window_Closed(object sender, EventArgs e)
        {
            var instance = CADInformationWindow.GetInstance();
            if (instance != null)
            {
                instance.Show();
            }
        }




        static string dll = @"D:\Project\ZXZK\ZhuXingFamilys\bin\Debug\TD_Mgd\TD_Mgd.dll";//引用位置
        Assembly a = Assembly.UnsafeLoadFrom(dll);
        string name = "";

        // 提取按钮
        private void line_Button_Click(object sender, RoutedEventArgs e)
        {
            this.Hide();
            var doc = uiApp.ActiveUIDocument.Document;
            var uiSel = uiApp.ActiveUIDocument.Selection;

            try
            {
                // 让用户选择一个图元上的点
                var reference = uiSel.PickObject(ObjectType.PointOnElement, "点击图元上的点，按ESC退出");

                // 获取选择的图元
                var element = doc.GetElement(reference);

                // 根据选择的图元参考获取其几何对象
                var geoObj = element.GetGeometryObjectFromReference(reference);

                if (geoObj != null && geoObj.GraphicsStyleId != ElementId.InvalidElementId)
                {
                    XYZ p1 = null;
                    XYZ p2 = null;
                    // var name = "";
                    var id = "";

                    if (geoObj is Line)
                    {
                        Line l = geoObj as Line;
                        p1 = l.GetEndPoint(0);
                        p2 = l.GetEndPoint(1);
                    }
                    if (p1.Y == p2.Y)
                    {

                        GraphicsStyle gs = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle;

                        if (gs != null)
                        {
                            // 获取选中图元的CAD图层
                            Category targetCategory = gs.GraphicsStyleCategory;

                            // 获取CAD图层的名称
                            name = targetCategory.Name;


                             lineCategories.Add(new SelectedLayers
                            {
                                selectedReference = reference,
                                selectedCategory = targetCategory,
                                AxisLineName = name,
                                AxisLineStartPoint = p1,
                                AxisLineEndPoint = p2
                            });


                        }

                        MessageBox.Show($"线的编号:{geoObj},轴网线的名字:{name},起点:{p1.ToString()},终点:{p2.ToString()}");
                    }
                    else
                    {
                        MessageBox.Show("选的线不是横坐标的线");
                    }
                }
            }
            // 捕获用户取消操作的异常
            catch (Autodesk.Revit.Exceptions.OperationCanceledException)
            {
                // 忽略异常继续执行
            }

            // 显示当前窗口
            this.Show();
        } 







        // 线层删除
        private void line_Button_delete(object sender, RoutedEventArgs e)
        {
            if (lineListBox.SelectedItem != null)
            {
                var c = lineListBox.SelectedItem;
                lineListBox.Items.Remove(c);
                lineCategories.RemoveAll(item => item.selectedCategory.Name == c.ToString());
            }
        }

    // 符号层提取按钮
    private void symbol_Button_Click(object sender, RoutedEventArgs e)
    {
        this.Hide();
        var doc = uiApp.ActiveUIDocument.Document;
        var uiSel = uiApp.ActiveUIDocument.Selection;
        try
        {
            var reference = uiSel.PickObject(ObjectType.PointOnElement, "点击图元上的点，按ESC退出");
            var element = doc.GetElement(reference);
            var geoObj = element.GetGeometryObjectFromReference(reference);
            if (geoObj.GraphicsStyleId != ElementId.InvalidElementId)
            {
                GraphicsStyle gs = doc.GetElement(geoObj.GraphicsStyleId) as GraphicsStyle;
                    if (gs != null)
                    {
                        Category targetCategory = gs.GraphicsStyleCategory;
                        var name = gs.GraphicsStyleCategory.Name;

                        // 将提取的符号信息添加到列表中
                        symbolCategories.Add(new SelectedLayers
                        {
                            selectedReference = reference,
                            selectedCategory = targetCategory,
                            LabelName = name,
                            LabelPosition = reference.GlobalPoint
                        });

                        symbolListBox.Items.Add(name);
                    }
                }
        }
        catch (Autodesk.Revit.Exceptions.OperationCanceledException)
        {

        }
        this.Show();
    }

    // 符号层删除
    private void symbol_Button_delete(object sender, RoutedEventArgs e)
        {
            if (symbolListBox.SelectedItem != null)
            {
                var c = symbolListBox.SelectedItem;
                symbolListBox.Items.Remove(c);
                symbolCategories.RemoveAll(item => item.selectedCategory.Name == c.ToString());
            }
        }


    // 开始识别
    private void identify_Button_Click(object sender, RoutedEventArgs e)
        {
            // 显示进度条
            progressBar.Visibility = System.Windows.Visibility.Visible;

            // 设置进度条的值为 100（这里看似设置为 100，可以根据实际需求调整）
            progressBar.Value = 100;

            // 获取 CADInformationWindow 实例
            var instance = CADInformationWindow.GetInstance();

            // 通过 CADInformationWindow 实例读取 CAD 信息，传递轴线和符号的相关信息
            instance.ReadCAD(CAD.classification, lineCategories, symbolCategories);

            // 创建外部事件对象
            ExternalEvent readCadEvent = null;

            // 创建 CADInformationWindow 对象，传递 Revit 的 UIApplication 和外部事件
            CADInformationWindow otherPage = new CADInformationWindow(uiApp, readCadEvent);

            // 显示 CADInformationWindow 窗口
            otherPage.Show();

        }
    }
}
